/*//////////////////////////
///////20120204/////////
/////Shim sang woo/////
////////G-sensor/////////
*///////////////////////////

package com.example.ddakji;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class move_Camera extends Activity implements SensorEventListener{ 

	Vibrator vibrator;	//진동?�용
	
    private long lastTime; 
    private float speed; 
    private float lastX; 
    private float lastY; 
    private float lastZ; 
    private float x, y, z; 

    private static final int SHAKE_THRESHOLD = 800; 
    @SuppressWarnings("deprecation")
	private static final int DATA_X = SensorManager.DATA_X; 
    @SuppressWarnings("deprecation")
	private static final int DATA_Y = SensorManager.DATA_Y; 
    @SuppressWarnings("deprecation")
	private static final int DATA_Z = SensorManager.DATA_Z; 

    private SensorManager sensorManager; 
    private Sensor accelerormeterSensor;
 
    boolean cap = false;
    
    public static String IMAGE_FILE = "capture.jpg";
    
    CameraSurfaceView cameraView;
    
    TextView text1, text2, text3;
    
    
    //////////////////////��ġ�� �̹��� �۾�///////////////////////
    ImageSwitcher switcher; 
	Handler mHandler = new Handler();
	ImageThread thread; //������ �ִϸ��̼��� ������ ������
	
	boolean running; 
	
	Animation_Class animation_class = new Animation_Class();
    //////////////////////��ġ�� �̹��� �۾�///////////////////////
	
	
	
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);		//?�에 ?�목�???��
	//	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //?�면 꺼짐 방�?
		
        setContentView(R.layout.move_camera);

        //cameraView = new CameraSurfaceView(getApplicationContext());
        //RelativeLayout previewFrame = (RelativeLayout) findViewById(R.id.relative1);
        //previewFrame.addView(cameraView);		//카메??보임
        
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);	//진동?�용
        
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
        accelerormeterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        
        text1 = (TextView)findViewById(R.id.textView1);
        text2 = (TextView)findViewById(R.id.textView2);
        text3 = (TextView)findViewById(R.id.textView3);

       
        switcher = (ImageSwitcher) findViewById(R.id.switcher);
        		switcher.setVisibility(View.VISIBLE);
        
        switcher.setFactory(new ViewSwitcher.ViewFactory(){
        	public View makeView() {
        		ImageView imageView = new ImageView(getApplicationContext());
        		//imageView.setBackgroundColor(0xFF000000);
        		imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        		imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
        				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        		return imageView;
        	}
        });
        
        switcher.setImageResource(R.drawable.ndak1); //ùȭ�鿡 ���� ù������ �����
    } 
    

   
    @Override 
    public void onStart() { 
        super.onStart(); 
        if (accelerormeterSensor != null) 
            sensorManager.registerListener(this, accelerormeterSensor, 
                    SensorManager.SENSOR_DELAY_GAME); 
    } 

    @Override 
    public void onStop() { 
        super.onStop(); 
        if (sensorManager != null) 
            sensorManager.unregisterListener(this); 
    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 
    } 

    
    @SuppressWarnings("deprecation")
	@Override 
    public void onSensorChanged(SensorEvent event) { 

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
            long currentTime = System.currentTimeMillis(); 
            long gabOfTime = (currentTime - lastTime); 

            x = event.values[SensorManager.DATA_X]; 
            y = event.values[SensorManager.DATA_Y]; 
            z = event.values[SensorManager.DATA_Z]; 
            speed = Math.abs(x + y + z - lastX - lastY - lastZ) / gabOfTime * 10000;
            
            //text1.setText(""+x);
            //text2.setText(""+y);
            text3.setText(""+z);
            
            if (gabOfTime > 90&&z>7) {
                lastTime = currentTime; 
                if (speed > SHAKE_THRESHOLD&& speed > 2300) { 
                	cap = true;
                	Toast.makeText(getApplicationContext(),""+speed,Toast.LENGTH_SHORT).show();	
                	//?�재 �?�� 빠�???메소???�행 => 멈춘 ???�행?�로 교체
                }
                else if(speed<1300&&cap){
                	cap=false;	
                	try {
						Thread.sleep(30);
						vibrator.vibrate((long)speed/3);//?�깐 ?�린??
						Click_Event();
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                	/*
                	cameraView.capture(new Camera.PictureCallback() {
                        public void onPictureTaken(byte[] data, Camera camera) {
                        	
                            try {
                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                String outUriStr = MediaStore.Images.Media.insertImage(getContentResolver(),bitmap, "Captured Image", "Captured Image using Camera.");
                                
                                if (outUriStr == null) {
                                    Log.d("SampleCapture", "Image insert failed.");
                                    return;
                                } else {
                                    Uri outUri = Uri.parse(outUriStr);
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, outUri));
                                }
                                Toast.makeText(getApplicationContext(), "?�진촬영 ?�료", Toast.LENGTH_LONG).show();
                                camera.startPreview();
                            } catch (Exception e) {
                                Log.e("SampleCapture", "Failed to insert image.", e);
                            }
                        	camera.startPreview();
                        }
                    });*/
                }
                lastX = event.values[DATA_X]; 
                lastY = event.values[DATA_Y]; 
                lastZ = event.values[DATA_Z]; 
            } 
        } 
    }  
    
    public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
    	
    	private SurfaceHolder mHolder;
    	private Camera camera = null;
    	
    	@SuppressWarnings("deprecation")
    	public CameraSurfaceView(Context context) {
    		super(context);
    		// TODO Auto-generated constructor stub
    		
    		mHolder = getHolder();
    		mHolder.addCallback(this);
    		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    	}

    	@Override
    	public void surfaceCreated(SurfaceHolder holder) {
    		// TODO Auto-generated method stub
    		camera = Camera.open();
    		
    		try {
    			camera.setPreviewDisplay(mHolder);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}

    	@Override
    	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    		// TODO Auto-generated method stub
    		camera.startPreview();
    	}
    	
    	@Override
    	public void surfaceDestroyed(SurfaceHolder holder) {
    		// TODO Auto-generated method stub
    		camera.stopPreview();
    		camera = null;
    	}
    	
    	public boolean capture(Camera.PictureCallback handler){
    		if(camera !=null){
    			camera.takePicture(null, null, handler);
    			return true;
    		}else{
    			return false;
    		}
    	}
    }

    
    
    ////////////////////////////��ġ�� �̹��� �۾�//////////////////////////
    private void Click_Event(){
  		
  		 Animation anim_up = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scaleup);
  	     final Animation anim_down = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.scaledown); //Ŀ���� �۾����� Ʈ�� �ִϸ��̼�
  	     anim_up.setInterpolator(new DecelerateInterpolator()); //Ʈ�� �ִϸ��̼� �ӵ� ����
   		 anim_down.setInterpolator(new AccelerateInterpolator());
  		startAnimation();	//������ �ִϸ��̼� ����
  		
  		switcher.startAnimation(anim_up); //Ŀ���� Ʈ��  �ִϸ��̼� ���� 
  		anim_up.setAnimationListener(new AnimationListener(){
  			
  		public void onAnimationEnd(Animation _animation) {
  			switcher.startAnimation(anim_down);	//Ŀ���� Ʈ�� �ִϸ��̼� �����ϸ� �۾����� Ʈ�� �ִϸ��̼� ����
  		}
  		public void onAnimationRepeat(Animation _animation) {		}
  		public void onAnimationStart(Animation _animation) { 		}		
  		});
  		
  		anim_down.setAnimationListener(new AnimationListener(){
  			public void onAnimationEnd(Animation _animation) {
  				 stopAnimation(); 	//�۾����� Ʈ�� �ִϸ��̼� �����ϸ� �����Ӿִϸ��̼� ��������
      		}
      		public void onAnimationRepeat(Animation _animation) {		}
      		public void onAnimationStart(Animation _animation) { 		}		
      		});
  		

}
    private void startAnimation()	//������ �ִϸ��̼� ����
    { 
    	thread = new ImageThread();
    	thread.start();	//������ ����
    }
    
    
    private void stopAnimation() //������ �ִϸ��̼� ����
    {
    	running = false;
    	try {
    		thread.join(); //������ ������� ���
    	} catch(InterruptedException ex){}
    	//switcher.setVisibility(View.INVISIBLE);
    }
    
    class ImageThread extends Thread {
    	
    	float duration = 10; //ù ������ ���۰�
    	
    	final int imageId[] = { R.drawable.ndak1,
    			R.drawable.ndak2,
    			R.drawable.ndak3,
    			R.drawable.ndak4,
    			R.drawable.ndak5,
    			R.drawable.ndak6,
    			R.drawable.ndak7,
    			R.drawable.ndak8,
    			R.drawable.ndak9,
    			R.drawable.ndak10,
    			R.drawable.ndak11,
    			R.drawable.ndak12,
    			R.drawable.ndak13,
    			R.drawable.ndak14,
    			R.drawable.ndak15,
    			R.drawable.ndak16,
    			R.drawable.ndak17,
    			R.drawable.ndak18,
    			R.drawable.ndak19,
    			R.drawable.ndak20
    			}; //���� �ѹ��� ���� ������
    	int currentIndex = 0;
    	 
    	public void run(){
    		running = true;
    		while(running) {
    			synchronized(this){
    				mHandler.post(new Runnable() {
    					public void run(){
    						
    						switcher.setImageResource(imageId[currentIndex]);
    						duration+=100/81;
    					}
    				});
    				currentIndex++;
    				
    				if(currentIndex == imageId.length){
    					currentIndex = 0;
    				}
    				
    				
    				try {
    					Thread.sleep((int)duration);
    				} catch (InterruptedException ex){}
    				
    				/*if (count == 90) {
    					count = 0;
    		    		stopAnimation();
    		    		
    				}*/
    			}
    		}
    	}
    }
    ////////////////////////////��ġ�� �̹��� �۾�//////////////////////////
    
}
